<template>
  <div>
    <div class="topbg" v-if="route.query.copyrightOwnerId">
      <el-button type="primary" @click="goBack">上一页 </el-button>
    </div>
    <TableSearch
      :query="query"
      :options="searchOpt"
      :search="handleSearch"
      @reset-search="handleresetSearch"
    >
      <template #parent>
        <el-cascader
          v-model="tagIdListShow"
          :options="cascaderOptions"
          :props="{ checkStrictly: true, multiple: true }"
          @change="handleChangeSeach"
          clearable
          placeholder="请选择歌曲标签"
        />
      </template>
    </TableSearch>
    <div class="container">
      <TableCustom
        :columns="columns"
        :tableData="tableData"
        :total="page.total"
        :currentPage="page.currPage"
        :viewFunc="handleView"
        :delFunc="handleDelete"
        :change-page="changePage"
        :editFunc="handleEdit"
        :upFunc="handleUpSong"
        :downFunc="handleDownSong"
        :downFuncSong="handleDownSongXia"
        :trackFilekList="handleTrackFilekList"
        :collectSongFunc="handleCollectSongFunc"
        :setRecommendedFunc="handleSetRecommended"
        :yichRecommendedFunc="handleYichRecommended"
        :change-cell="changeCell"
        :changeCellMouseEnter="changeCellMouseEnter"
        :changeCellMouseLeave="changeCellMouseLeave"
        :tableRowClassName="tableRowClassName"
      >
        <template #toolbarBtn>
          <div class="daoru">
            <el-button
              type="warning"
              :icon="CirclePlusFilled"
              @click="handleAdd"
              >新增</el-button
            >
            <div class="daoru2">
              <el-button
                class="mr10"
                type="warning"
                plain
                @click="downloadExcelSong"
                >导出歌曲</el-button
              >
              <el-dropdown class="mr10">
                <el-button type="primary" plain>
                  批量打标签
                  <el-icon class="el-icon--right">
                    <arrow-down />
                  </el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu size="small">
                    <el-dropdown-item command="other"
                      ><el-upload
                        action="http://129.204.225.193:8890/web/song/excelUpdateTag"
                        :limit="1"
                        accept=".xlsx, .xls"
                        :data="uploadData"
                        :file-list="fileList"
                        :before-upload="beforeUpload2"
                        :on-success="handleUploadSuccess2"
                        :show-file-list="false"
                      >
                        <el-button class="mr10" type="success" plain
                          >上传文件</el-button
                        >
                      </el-upload></el-dropdown-item
                    >
                    <el-dropdown-item command="current"
                      ><el-button
                        class="mr10"
                        plain
                        type="primary"
                        @click="downloadTagTemplate"
                        >下载模版</el-button
                      ></el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <el-upload
                action="http://129.204.225.193:8890/web/song/excelUploadSong"
                :limit="1"
                accept=".xlsx, .xls"
                :data="uploadData"
                :file-list="fileList"
                :before-upload="beforeUpload"
                :on-success="handleUploadSuccess"
                :show-file-list="false"
              >
                <el-button class="mr10" type="success">批量导入</el-button>
              </el-upload>
              <el-button type="primary" plain @click="downloadTemplate"
                >下载模板</el-button
              >
            </div>
          </div>
        </template>
        <!-- 歌曲/专辑封面 -->
        <template #coverUrl="{ rows }">
          <div class="zhuanj">
            <el-image
              :src="rows.coverUrl.indexOf('http') === -1 ? '' : 'rows.coverUrl'"
              fit="cover"
              class="avatar"
            ></el-image>
            <!-- <div class="zhuanj_bg"></div>
            <img
              class="zhuanj_img1"
              v-if="rows.index === yiruIndex"
              src="@/assets/img/play.png"
            />
            <img
              class="zhuanj_img2"
              v-if="rows.index === yiruIndex && rows.index === bofangIndex"
              src="@/assets/img/puase.png"
            /> -->
          </div>
        </template>
        <!-- 歌词类型：0-无 1-静态，2-LRC，3-KRC -->
        <template #lyricType="{ rows }">
          <el-popover
            effect="light"
            trigger="hover"
            placement="top"
            width="auto"
          >
            <template #default>
              <div>下载歌词</div>
            </template>
            <template #reference>
              {{
                rows.lyricType === 1
                  ? "静态"
                  : rows.lyricType === 2
                  ? "LRC"
                  : rows.lyricType === 3
                  ? "KRC"
                  : "无"
              }}
            </template>
          </el-popover>
        </template>
        <!-- 时长 -->
        <template #duration="{ rows }">
          <div>{{ secondsToHms(rows.duration) }}</div>
        </template>
        <template #isOffline="{ rows }">
          <el-tag type="success" v-if="rows.isOffline === 0">上架</el-tag>
          <el-tag type="danger" v-else>下架</el-tag>
        </template>
        <!-- 是否为上新推荐 -->
        <template #isRecommended="{ rows }">
          <el-tag type="success" v-if="rows.isRecommended === 1">是</el-tag>
          <el-tag type="danger" v-else>否</el-tag>
        </template>
      </TableCustom>
    </div>
    <el-dialog
      :title="isEdit ? '编辑' : '新增'"
      v-model="visible"
      width="700px"
      destroy-on-close
      :close-on-click-modal="closeDialog"
      @close="closeDialog"
    >
      <TableEdit
        :form-data="rowData"
        :options="options"
        :edit="isEdit"
        :update="updateData"
        @closeDialogP="closeDialog"
      >
        <template #parent>
          <el-cascader
            placeholder="请选择歌曲标签"
            v-model="selectParentTagId"
            :options="cascaderOptions"
            :props="{ checkStrictly: true, multiple: true }"
            clearable
          /> </template
      ></TableEdit>
    </el-dialog>
    <el-dialog title="详情" v-model="visible1" width="1000px" destroy-on-close>
      <TableDetail :data="viewData" @closeDialogP="visible1 = false">
        <!-- 歌曲波形图 -->
        <template #oscillogramJsonUrl="{ rows }">
          <div ref="waveform">
            <span
              style="display: none"
              v-if="
                rows.haveSongFile === 1 &&
                rows.songFileUrl &&
                rows.songFileUrl.indexOf('http') !== -1
              "
              >{{ initBoXingTu(rows) }}</span
            >
            <span v-else class="redTishi">无法根据音频文件地址生成波形图</span>
          </div>
        </template>
        <!-- 歌词类型：0-无 1-静态，2-LRC，3-KRC -->
        <template #lyricType="{ rows }">
          <div>
            {{
              rows.lyricType === 1
                ? "静态"
                : rows.lyricType === 2
                ? "LRC"
                : rows.lyricType === 3
                ? "KRC"
                : "无"
            }}
          </div>
        </template>
        <!-- 是否CC0：0-否，1-是 -->
        <!-- <template #isCc0="{ rows }">
          <div v-if="rows.isCc0 === 1">是</div>
          <div v-else-if="rows.isCc0 === 0">否</div>
        </template> -->
        <!-- 歌词文件地址 -->
        <template #lyricFileUrl="{ rows }">
          <a
            :href="rows.lyricFileUrl"
            target="_blank"
            v-if="rows.lyricFileUrl"
            >{{ rows.lyricFileUrl }}</a
          >
          <span v-else class="redTishi">暂无信息</span>
        </template>
        <!-- 歌曲文件地址 -->
        <template #songFileUrl="{ rows }">
          <a
            :href="rows.songFileUrl"
            target="_blank"
            v-if="
              rows.haveSongFile === 1 &&
              rows.songFileUrl &&
              rows.songFileUrl.indexOf('http') !== -1
            "
            >{{ rows.songFileUrl }}</a
          >
          <span v-else-if="rows.haveSongFile === 0" class="redTishi"
            >音频文件地址有误，请重新上传正确的地址</span
          >
          <span v-else class="redTishi">暂无信息</span>
        </template>
        <!-- 封面 -->
        <template #coverUrl="{ rows }">
          <el-image
            v-if="rows.coverUrl && rows.coverUrl.indexOf('http') !== -1"
            :src="rows.coverUrl"
            fit="cover"
            class="avatar"
          ></el-image>
        </template>
        <!-- 时长 -->
        <template #duration="{ rows }">
          <div>{{ secondsToHms(rows.duration) }}</div>
        </template>
        <!-- 是否为上新推荐 -->
        <template #isRecommended="{ rows }">
          <el-tag type="success" v-if="rows.isRecommended === 1">是</el-tag>
          <el-tag type="danger" v-else>否</el-tag>
        </template>
        <!-- 是否下架 -->
        <template #isOffline="{ rows }">
          <el-tag type="success" v-if="rows.isOffline === 0">上架</el-tag>
          <el-tag type="danger" v-else>下架</el-tag>
        </template>
      </TableDetail>
    </el-dialog>
    <!-- 子版本抽屉 -->
    <el-drawer
      v-model="drawer"
      direction="rtl"
      :title="drawerTitle"
      :before-close="handleClose"
      append-to-body
      size="60%"
    >
      <subversion-list
        :songId="songIdSelect"
        :type="typeSelect"
        ref="childRef"
        :isDrawer="drawer"
      ></subversion-list>
    </el-drawer>
    <!-- 收藏歌曲到歌单弹框 -->
    <el-drawer
      v-model="drawer2"
      direction="rtl"
      title="歌单列表"
      :before-close="handleClose"
      append-to-body
      size="60%"
    >
      <PlayList
        :songId="songIdSelect"
        :type="typeSelect"
        ref="childRef"
        :isDrawer="drawer2"
      ></PlayList>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import axios from "axios";
import { ref, onMounted, reactive, watch } from "vue";
import { ElMessage, UploadProps, ElNotification } from "element-plus";
import { CirclePlusFilled } from "@element-plus/icons-vue";
import { User } from "@/types/user";
import {
  fetchGetCopyrightOwnerSelect,
  fetchSonglistData,
  fetchSongCreate,
  fetchDeleteSong,
  fetchSoldInSong,
  fetchSoldOutSong,
  fetchGetObsUrl,
  fetchDownloadTemplate,
  fetchDownloadSong,
  fetchSetRecommended,
  fetchDeleteRecommended,
  fetchExcelDownloadSong,
  fetchUpdateTagTemplate,
} from "@/api/musicLibrary";
import {
  fetchSongCategoryData,
  fetchSongTagTreeData,
} from "@/api/configuration";
import TableCustom from "@/components/table-custom.vue";
import TableDetail from "@/components/table-detail.vue";
import TableSearch from "@/components/table-search.vue";
import SubversionList from "@/views/musicLibrary/subversionList.vue";
import PlayList from "@/views/musicLibrary/playList.vue";
import { FormOption, FormOptionList } from "@/types/form-option";
import { ElLoading } from "element-plus";
import { saveAs } from "file-saver";
import WaveSurfer from "wavesurfer.js";
import { useRouter, useRoute } from "vue-router";
import { get } from "@vueuse/core";
// import { useWebSocketRealTime } from "@/utils/useWebSocketRealTime";
import useWebSocket from "@/services/websocketService"; // 根据实际情况调整路径
// import useWebSocket from "./useWebSocket";
const router = useRouter();
const goBack = () => {
  router.go(-1);
};

// 时长换算
const secondsToHms = (seconds) => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;
  return `${minutes.toString().padStart(2, "0")}:${secs
    .toString()
    .padStart(2, "0")}`;
};

const tagIdListShow = ref([]);
// 查询相关
const query = reactive({
  keyword: "",
  tagIdList: [], //标签id
  copyrightOwnerIdList: [], //版权方id,可多选
  lyricType: "", //歌词类型
  songId: "", //歌曲id
  songVersion: "", //歌曲版本
});

const route = useRoute(); // 新增这一行
const copyrightOwnerId = route.query.copyrightOwnerId; // 获取动态参数
console.log("获取前一个页面的数据");
console.log(route.query);
if (copyrightOwnerId) {
  query.copyrightOwnerIdList.push(copyrightOwnerId);
}

const handleChangeSeach = (value) => {
  const tagIdListFi = ref([]);
  console.log("头部--搜索条件--选择标签");
  console.log(query.tagIdList);
  if (query.tagIdList && query.tagIdList.length > 0) {
    query.tagIdList.forEach((item, index) => {
      console.log("走-1");
      console.log(item);
      tagIdListFi.value.push(item[item.length - 1]);
    });
  }
  // query.tagIdList = tagIdListFi.value;
  getData();
};

const searchOpt = ref<FormOptionList[]>([
  {
    type: "input",
    label: "关键字搜索：",
    prop: "keyword",
    placeholder: "请输入关键字",
  },
  {
    type: "parent",
    label: "歌曲标签",
    prop: "parent",
    placeholder: "请选择歌曲标签",
  },
  {
    type: "select",
    label: "版权方",
    prop: "copyrightOwnerIdList",
    multiple: true,
    opts: [],
    placeholder: "请选择版权方",
  },
  {
    type: "select",
    label: "歌词类型",
    prop: "lyricType",
    opts: [
      { label: "无", value: 0 },
      { label: "静态", value: 1 },
      { label: "LRC", value: 2 },
      { label: "KRC", value: 3 },
    ],
    placeholder: "请选择歌词类型",
  }, //歌词类型：0-无 1-静态，2-LRC，3-KRC
  // {
  //   type: "input",
  //   label: "歌曲ID：",
  //   prop: "songId",
  //   placeholder: "请输入歌曲ID",
  // },
  // {
  //   type: "input",
  //   label: "歌曲版本：",
  //   prop: "songVersion",
  //   placeholder: "请输入歌曲版本",
  // },
]);

const handleresetSearch = () => {
  query.tagIdList = [];
  getData();
};

const handleSearch = () => {
  changePage(1);
};

// 表格相关
let columns = ref([
  { type: "index", label: "序号", width: 80, align: "center" },
  // { prop: "songId", label: "歌曲ID", width: 150 },
  // { prop: "coverUrl", label: "歌曲/专辑封面", width: 150 },
  { prop: "songName", label: "歌曲名称", width: 300 },
  // { prop: "isRecommended", label: "是否为上新推荐", width: 150 }, //是否为上新推荐：0-否，1-是
  // { prop: "tagNameList", label: "歌曲标签", width: 150 },
  // { prop: "songDesc", label: "歌曲描述", width: 150 },
  // { prop: "songVersion", label: "歌曲版本", width: 150 },
  // { prop: "performer", label: "表演者", width: 150 },
  // { prop: "lyricist", label: "词作者", width: 150 },
  // { prop: "composer", label: "曲作者", width: 150 },
  // { prop: "lyricType", label: "歌词类型", width: 150 }, //歌词类型：0-无 1-静态，2-LRC，3-KRC
  { prop: "copyrightOwner", label: "版权方" },
  // { prop: "manufacturer", label: "厂商", width: 150 },
  // { prop: "recordLabel", label: "厂牌", width: 150 },
  { prop: "albumName", label: "专辑名" },
  // { prop: "bpm", label: "BPM", width: 150 },
  { prop: "duration", label: "时长" },
  // { prop: "subVersionCount", label: "关联子版本数", width: 180 },
  // { prop: "trackFileCount", label: "关联分轨文件数", width: 180 },
  { prop: "isOffline", label: "是否下架" }, //是否下架：0-否，1-是
  { prop: "createTime", label: "创建时间" },
  { prop: "operator", label: "操作", width: 300, fixed: "right" },
]);
const page = reactive({
  currPage: 1,
  size: 10,
  total: 0,
});
const tableData = ref([]);
const getData = async () => {
  let obj_1 = {
    currPage: page.currPage,
    size: page.size,
  };
  const tagIdListFi = ref([]);
  if (tagIdListShow.value && tagIdListShow.value.length > 0) {
    tagIdListShow.value.forEach((item, index) => {
      console.log("重新改变数据");
      console.log(item);
      tagIdListFi.value.push(item[item.length - 1]);
    });
  } else {
    query.tagIdList = [];
  }
  query.tagIdList = tagIdListFi.value;
  let params = { ...query, ...obj_1 };
  const res = await fetchSonglistData(params);
  console.log("曲库管理1222");
  console.log(res.data);
  let list = res.data.data.records;
  let obj = {};
  if (list.length > 0) {
    list.forEach((item, index) => {
      if (Array.isArray(item.categoryNameList)) {
        item.categoryNameList = item.categoryNameList.join(",");
      }
      if (Array.isArray(item.tagNameList)) {
        item.tagNameList = item.tagNameList.join(",");
      }
      item.pageName = "musicLibraryList";
      item.index = index;
    });
  }

  tableData.value = res.data.data.records;
  page.total = res.data.data.total;
  console.log(page.total);
};
getData();

// 分页
const changePage = (val: number) => {
  console.log("点击分页---歌单分类管理");

  page.currPage = val;
  console.log(page.currPage);
  getData();
};

// 获取-歌曲分类选项列表
const getCategoryList = async () => {
  let params = {
    currPage: 1,
    size: 1000,
    isShowNoCount: 1,
  };
  const res = await fetchSongCategoryData(params);

  let list = res.data.data.records;
  list.forEach((item) => {
    item.value = item.songCategoryId;
    item.label = item.categoryName;
  });
  options.value.list[2].opts = list;
};

getCategoryList();

const menuData = ref([]);
const cascaderOptions = ref([]);
const getOptions = (data: any) => {
  return data.map((item) => {
    const a: any = {
      label: item.tagName,
      value: item.songTagId,
      tagLevel: item.tagLevel,
      remark: item.remark,
      parentTagId: item.parentTagId,
    };
    if (item.songTagList) {
      a.children = getOptions(item.songTagList);
    }
    return a;
  });
};
// 获取-歌曲标签树
const getSongTag = async () => {
  let params = {
    isShowNoCount: 1, //是否显示没有歌曲的标签 0-否 1-是
  };
  const res = await fetchSongTagTreeData(params);
  console.log("获取歌曲标签树");
  console.log(res.data);
  menuData.value = res.data.data;
  console.log(menuData.value);
  // page.total = res.data.data.total;
  // console.log(page.total);
  cascaderOptions.value = getOptions(menuData.value);
  console.log("11111");
  console.log(cascaderOptions.value);
};
getSongTag();

const copyrightOwnerOpts = ref([]);
// 获取版权方下拉框
const getCopyrightOwner = async () => {
  const res = await fetchGetCopyrightOwnerSelect({});
  let list = res.data.data;
  list.forEach((item) => {
    item.label = item.value;
    item.value = item.id;
  });
  console.log("版权方下拉框");
  console.log(list);
  options.value.list[13].opts = list;
  searchOpt.value[2].opts = list;
  copyrightOwnerOpts.value = list;
};

getCopyrightOwner();

// 新增/编辑弹窗相关
let options = ref<FormOption>({
  labelWidth: "120px",
  span: 24,
  list: [
    {
      type: "input",
      label: "歌曲名称",
      prop: "songName",
      required: true,
      placeholder: "请输入歌曲名称",
    },
    {
      type: "input",
      label: "专辑名",
      prop: "albumName",
      placeholder: "请输入专辑名",
    },
    {
      type: "select",
      label: "歌曲分类",
      prop: "categoryIdList",
      multiple: true,
      opts: [],
      placeholder: "请选择歌曲分类",
    },
    {
      type: "parent",
      label: "歌曲标签",
      prop: "parent",
      placeholder: "请选择歌曲标签",
    },
    {
      type: "input",
      label: "副歌开始时间（秒）",
      prop: "chorusBeginTime",
      placeholder: "请输入副歌开始时间",
    },
    {
      type: "input",
      label: "副歌结束时间（秒）",
      prop: "chorusEndTime",
      placeholder: "请输入副歌结束时间",
    },
    {
      type: "input",
      label: "曲作者",
      prop: "composer",
      placeholder: "请输入曲作者",
    },
    {
      type: "input",
      label: "词作者",
      prop: "lyricist",
      placeholder: "请输入词作者",
    },
    {
      type: "input",
      label: "厂商",
      prop: "manufacturer",
      placeholder: "请输入厂商",
    },
    {
      type: "input",
      label: "厂牌",
      prop: "recordLabel",
      placeholder: "请输入厂牌",
    },
    {
      type: "input",
      label: "表演者",
      prop: "performer",
      placeholder: "请输入表演者",
    },
    {
      type: "input",
      label: "歌曲描述",
      prop: "songDesc",
      placeholder: "请输入歌曲描述",
    },
    {
      type: "input",
      label: "歌曲版本",
      prop: "songVersion",
      placeholder: "请输入歌曲版本",
    },

    {
      type: "select",
      label: "版权方",
      prop: "copyrightOwnerId",
      opts: [],
      placeholder: "请选择版权方",
    },
    // {
    //   type: "switch",
    //   label: "是否CC0",
    //   prop: "isCc0",
    //   activeValue: 1,
    //   inactiveValue: 0,
    //   activeText: "是",
    //   inactiveText: "否",
    // }, //是否CC0：0-否，1-是
    {
      type: "select",
      label: "歌词类型",
      prop: "lyricType",
      opts: [
        { label: "无", value: 0 },
        { label: "静态", value: 1 },
        { label: "LRC", value: 2 },
        { label: "KRC", value: 3 },
      ],
      placeholder: "请选择歌词类型",
    }, //歌词类型：0-无 1-静态，2-LRC，3-KRC
    {
      type: "uploadLyric",
      label: "歌词文件地址",
      prop: "lyricFileUrl",
    },
    {
      type: "uploadSong",
      label: "歌曲文件地址",
      prop: "songFileUrl",
    },
    {
      type: "upload",
      label: "歌曲/专辑封面(请上传jpg，gif，png等图片格式)",
      prop: "coverUrl",
    },
  ],
});

const visible = ref(false);
const isEdit = ref(false);
const rowData = ref({});
const selectParentTagId = ref([]);

// 新增
const handleAdd = (row) => {
  console.log("新增");
  selectParentTagId.value = [];
  rowData.value = { ...row };
  isEdit.value = false;
  visible.value = true;
};

// 编辑
const handleEdit = (row) => {
  console.log("编辑");
  rowData.value = { ...row };
  selectParentTagId.value = row.tagIdList;
  isEdit.value = true;
  visible.value = true;
};
const updateData = async (data) => {
  const loading = ElLoading.service({
    lock: true,
    text: "保存中",
    background: "rgba(0, 0, 0, 0.7)",
  });
  let parentTagId = [];
  if (
    selectParentTagId.value &&
    Array.isArray(selectParentTagId.value) &&
    selectParentTagId.value.length > 0
  ) {
    selectParentTagId.value.forEach((item, index) => {
      console.log("走-1");
      console.log(item);
      if (Array.isArray(item)) {
        // parentTagId.push(item[0]);
        parentTagId.push(item[item.length - 1]);
      } else {
        parentTagId.push(item);
      }
      // parentTagId.push(item[item.length - 1]);
    });
  } else if (
    selectParentTagId.value &&
    typeof selectParentTagId.value === "string"
  ) {
    console.log("不处理");
  } else {
    parentTagId = [];
  }
  let datas = {};
  let copyrightOwner = ""; //版权方(通过选择的版权方id获取版权方名称)
  if (copyrightOwnerOpts.value && copyrightOwnerOpts.value.length > 0) {
    copyrightOwnerOpts.value.forEach((item, index) => {
      if (item.value === data.copyrightOwnerId) copyrightOwner = item.label;
    });
  }
  let obj = {
    tagIdList: parentTagId,
    copyrightOwner: copyrightOwner,
  };
  let editObi = { playlistId: data.playlistId };
  delete data.tagNameList;
  delete data.categoryNameList;
  if (isEdit.value) {
    datas = { ...data, ...obj, ...editObi };
  } else {
    datas = { ...data, ...obj };
  }
  console.log("最终编辑或者新增的数据---是");
  console.log(datas);
  const res = await fetchSongCreate(datas);

  loading.close();
  if (res.data.code == 0) {
    ElMessage.success("成功");
    getData();
  } else {
    ElMessage.error(res.data.msg);
  }
  closeDialog();
};

const closeDialog = () => {
  visible.value = false;
  isEdit.value = false;
};

// 详情弹窗相关
const visible1 = ref(false);
const viewData = ref({
  row: {},
  list: [],
});

// 波形图相关-----------------------start
const waveform = ref(null);
const wavesurfer = ref(null);
const handleView = (row) => {
  console.log("详情");
  console.log(row);

  // 重新绘制波形图
  if (wavesurfer.value) {
    console.log("销毁了吗");
    wavesurfer.value.destroy();
    if (row.songFileUrl && row.songFileUrl.indexOf("http") !== -1) {
      initBoXingTu(row);
    }
  } else {
    if (row.songFileUrl && row.songFileUrl.indexOf("http") !== -1) {
      initBoXingTu(row);
    }
  }
  viewData.value.row = { ...row };
  viewData.value.list = [
    {
      prop: "songId",
      label: "歌曲ID",
    },
    {
      prop: "songName",
      label: "歌曲名称",
    },
    {
      prop: "oscillogramJsonUrl",
      label: "歌曲波形图",
    },
    {
      prop: "albumName",
      label: "专辑名",
    },
    {
      prop: "tagNameList",
      label: "歌曲标签",
    },
    {
      prop: "categoryNameList",
      label: "歌曲分类",
    },
    {
      prop: "chorusBeginTime",
      label: "副歌开始时间（秒）",
    },
    {
      prop: "chorusEndTime",
      label: "副歌结束时间（秒）",
    },
    {
      prop: "duration",
      label: "时长",
    },
    {
      prop: "bpm",
      label: "BPM",
    },
    {
      prop: "subVersionCount",
      label: "关联子版本数",
    },
    {
      prop: "trackFileCount",
      label: "关联分轨文件数",
    },
    {
      prop: "composer",
      label: "曲作者",
    },
    {
      prop: "lyricist",
      label: "词作者",
    },
    {
      prop: "manufacturer",
      label: "厂商",
    },
    {
      prop: "recordLabel",
      label: "厂牌",
    },
    {
      prop: "performer",
      label: "表演者",
    },
    {
      prop: "songDesc",
      label: "歌曲描述",
    },
    {
      prop: "songVersion",
      label: "歌曲版本",
    },
    {
      prop: "copyrightOwner",
      label: "版权方",
    },
    {
      prop: "lyricType",
      label: "歌词类型",
    },
    // {
    //   prop: "isCc0",
    //   label: "是否CC0",
    // },
    {
      prop: "createTime",
      label: "创建时间",
    },
    {
      prop: "lyricFileUrl",
      label: "歌词文件地址",
    },
    {
      prop: "songFileUrl",
      label: "歌曲文件地址",
    },
    {
      prop: "coverUrl",
      label: "歌曲/专辑封面",
    },
    {
      prop: "isOffline",
      label: "是否下架",
    },
  ];
  visible1.value = true;
};

const initBoXingTu = async (songInfo) => {
  console.log("波形图初始化---lema");
  wavesurfer.value = WaveSurfer.create({
    container: waveform.value,
    progressColor: "#F92E53", // 未播放波形的颜色
    waveColor: "#999999",
    // 波形图的高度，单位为px
    height: 60,
    // 波形的振幅（高度），默认为1
    barHeight: 0.5,
    // 波形条的圆角
    barRadius: 2,
    // 波形条的宽度
    barWidth: 1,
    // 波形条间的间距
    barGap: 0,
    // 播放进度光标条的颜色
    cursorColor: "#999999",
    // 播放进度光标条的宽度，默认为1
    cursorWidth: 0,
    interact: false, // 禁用所有交互
  });
  if (songInfo.songFileUrl && songInfo.songFileUrl.indexOf("http") == -1) {
    console.log("需要通过key来获取歌曲路径");
    const res = await fetchGetObsUrl({ key: songInfo.songFileUrl });
    console.log(res);
    if (res.data.code === 0) {
      wavesurfer.value.load(
        res.data.data,
        getJsonData(songInfo.oscillogramJsonUrl)
      );
      wavesurfer.value.play();
    }
  } else {
    wavesurfer.value.load(
      songInfo.songFileUrl,
      getJsonData(songInfo.oscillogramJsonUrl)
    );
    wavesurfer.value.play();
  }
};
const getJsonData = (jsonUrl) => {
  axios
    .get(jsonUrl)
    .then((response) => {
      return response.data;
    })
    .catch((error) => {
      console.error("There was an error!", error);
    });
};
// 波形图相关---------------------end
// 删除相关
const handleDelete = async (row) => {
  console.log("删除11");
  console.log(row);
  let datas = {
    id: row.songId,
  };
  const res = await fetchDeleteSong(datas);
  if (res.data.code == 0) {
    ElMessage.success("删除成功");
    getData();
  }
};

// 上架歌曲
const handleUpSong = async (row) => {
  let arr = [];
  arr.push(row.songId);
  let datas = {
    songId: arr,
  };
  const res = await fetchSoldInSong(datas);
  if (res.data.code == 0) {
    ElMessage.success("上架成功");
    getData();
  }
};

// 下架歌曲
const handleDownSong = async (row) => {
  let arr = [];
  arr.push(row.songId);
  let datas = {
    songId: arr,
  };
  const res = await fetchSoldOutSong(datas);
  if (res.data.code == 0) {
    ElMessage.success("下架成功");
    getData();
  }
};

// 下载歌曲
const handleDownSongXia = async (row) => {
  console.log("下载歌曲");
  let datas = {
    songId: row.songId,
  };
  // 如果歌曲有歌曲文件地址---才能进行下载
  if (row.songFileUrl) {
    const res = await fetchDownloadSong(datas);
    if (res.data.code === 0) {
      // ElMessage.success("下载成功");
      downloadMusic(row);
    } else {
      ElMessage.error(res.data.msg);
    }
  } else {
    ElMessage.error("歌曲文件地址不存在,请在编辑操作里上传歌曲文件地址");
  }
};

const downloadMusic = (row) => {
  const loading = ElLoading.service({
    lock: true,
    text: "歌曲下载中",
    background: "rgba(0, 0, 0, 0.7)",
  });
  let path =
    row.songFileUrl + "?response-content-type=application/octet-stream";
  const xhr = new XMLHttpRequest();
  xhr.open("get", path);
  xhr.responseType = "blob";
  xhr.send();
  // xhr.progress = function () {
  //   console.log(this);
  // };
  xhr.onload = function () {
    if (this.status === 200 || this.status === 304) {
      const url = URL.createObjectURL(this.response);
      let a = document.createElement("a");
      a.href = url;
      a.download = row.songName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      loading.close();
      ElMessage.success("下载成功");
    }
  };
};

const drawer = ref(false);
const songIdSelect = ref("");
const typeSelect = ref(1);
const childRef = ref(null);
const drawerTitle = ref("子版本列表");
// 跳转子版本或者分轨文件
const handleTrackFilekList = async (row, type) => {
  if (type === 1) {
    console.log("跳转子版本文件");
    console.log(row);
    drawer.value = true;
    songIdSelect.value = row.songId;
    typeSelect.value = 1;
    drawerTitle.value = "子版本列表";
    console.log(row.value);
  } else {
    console.log("跳转分轨文件");
    drawer.value = true;
    songIdSelect.value = row.songId;
    typeSelect.value = 2;
    drawerTitle.value = "分轨列表";
  }
};
const handleClose = (done: () => void) => {
  done();
};

const drawer2 = ref(false);
//收藏歌曲到菜单
const handleCollectSongFunc = (row) => {
  songIdSelect.value = row.songId;
  drawer2.value = true;
};

const yiruIndex = ref(0); //移入的index
const bofangIndex = ref(-1); //播放的索引

// 点击单元格
const changeCell = (val, column, rowIndex, columnIndex) => {
  console.log("点击单元格");
  // console.log(val);
  // console.log(column, rowIndex, columnIndex);
  if (column.label == "歌词类型") {
    console.log("下载歌词");
    if (val.lyricFileUrl.includes("http")) {
      fetch(val.lyricFileUrl)
        .then((_) => _.blob())
        .then((_) => {
          const link = document.createElement("a");
          link.href = URL.createObjectURL(_);
          link.setAttribute("download", val.songName + "-歌词");
          link.click();
        });
    } else {
      ElMessage.error("歌词文件不存在");
    }
  }

  // 点击封面播放
  if (column.label == "歌曲/专辑封面") {
    if (bofangIndex.value === val.index) {
      console.log("点击暂停");
      bofangIndex.value = -1;
    } else {
      console.log("点击播放");
      bofangIndex.value = val.index;
    }
  }
};

// 移入某个单元格
const changeCellMouseEnter = (val, column, rowIndex, columnIndex) => {
  console.log("移入单元格");
  // console.log(rowIndex);
  // console.log(columnIndex);
  // console.log(val);
  // console.log(column, rowIndex, columnIndex);
  if (column.label == "歌曲/专辑封面") {
    console.log("歌曲/专辑封面");
    console.log(rowIndex);
    yiruIndex.value = val.index;
    // if (val.lyricFileUrl.includes("http")) {
    //   fetch(val.lyricFileUrl)
    //     .then((_) => _.blob())
    //     .then((_) => {
    //       const link = document.createElement("a");
    //       link.href = URL.createObjectURL(_);
    //       link.setAttribute("download", val.songName + "-歌词");
    //       link.click();
    //     });
    // } else {
    //   ElMessage.error("歌词文件不存在");
    // }
  }
};

// 移出某个单元格
const changeCellMouseLeave = (val, column, rowIndex, columnIndex) => {
  console.log("移出单元格");
  // console.log(val);
  // console.log(column, rowIndex, columnIndex);
  if (column.label == "歌曲/专辑封面") {
    console.log("歌曲/专辑封面");
    // yiruIndex.value = -1;
    // bofangIndex.value = -1;
  }
};

// 下载模版
const downloadTemplate = async () => {
  // const res = await fetchDownloadTemplate({});
  // console.log("下载模版");
  // console.log(res);
  // if (res.data.code == 0) {
  //   console.log(res.data);
  // }
  const operateAccountId = "admin";
  const operateAccountName = "系统管理员";

  fetch(
    `http://129.204.225.193:8890/web/song/excelDownloadTemplate?operateAccountId=${operateAccountId}&operateAccountName=${operateAccountName}`,
    {
      method: "GET",
    }
  )
    .then((res) => res.blob())
    .then((data) => {
      console.log("下载的数据");
      console.log(data);
      const blobUrl = window.URL.createObjectURL(data);
      const a = document.createElement("a");
      a.download = "歌曲模版.xlsx";
      a.href = blobUrl;
      a.click();
    });
};

// 导出歌曲excel，返回excel的url地址
const downloadExcelSong = async () => {
  let params = { ...query };
  const res = await fetchExcelDownloadSong(params);
  console.log("导出歌曲excel，返回excel的url地址");
  console.log(res.data);
  if (res.data.code == 0 && res.data.data) {
    // const blobUrl = window.URL.createObjectURL(res.data.data);
    const a = document.createElement("a");
    a.download = "歌曲列表.xlsx";
    a.href = res.data.data;
    a.click();
  }
  // let list = res.data.data.records;
};

// 下载excel批量给歌曲打标签模板
const downloadTagTemplate = async () => {
  const operateAccountId = JSON.parse(localStorage.getItem("userInfo")).userId
    ? JSON.parse(localStorage.getItem("userInfo")).userId
    : "admin";
  const operateAccountName = JSON.parse(localStorage.getItem("userInfo"))
    .userName
    ? JSON.parse(localStorage.getItem("userInfo")).userName
    : "系统管理员";

  fetch(
    `http://129.204.225.193:8890/web/song/excelUpdateTagTemplate?operateAccountId=${operateAccountId}&operateAccountName=${operateAccountName}`,
    {
      method: "GET",
    }
  )
    .then((res) => res.blob())
    .then((data) => {
      console.log("打标签模版的数据");
      console.log(data);
      const blobUrl = window.URL.createObjectURL(data);
      const a = document.createElement("a");
      a.download = "打标签模版.xlsx";
      a.href = blobUrl;
      a.click();
    });
  // let list = res.data.data.records;
};

var defaults = {};
if (localStorage.getItem("userInfo")) {
  defaults = {
    operateAccountId: JSON.parse(localStorage.getItem("userInfo")).userId,
    operateAccountName: JSON.parse(localStorage.getItem("userInfo")).userName,
  };
} else {
  defaults = {
    operateAccountId: "admin",
    operateAccountName: "系统管理员",
  };
}

const uploadData = defaults;
let loading = null;
// 通过excel上传歌曲---成功后--请求列表
const beforeUpload = (file) => {
  loading = ElLoading.service({
    lock: true,
    text: "导入中",
    background: "rgba(0, 0, 0, 0.7)",
  });
  const formData = new FormData();
  formData.append("file", file);
  // 可以添加其他字段
  const operateAccountId = JSON.parse(localStorage.getItem("userInfo")).userId
    ? JSON.parse(localStorage.getItem("userInfo")).userId
    : "admin";
  const operateAccountName = JSON.parse(localStorage.getItem("userInfo"))
    .userName
    ? JSON.parse(localStorage.getItem("userInfo")).userName
    : "系统管理员";
  formData.append("operateAccountId", operateAccountId);
  formData.append("operateAccountName", operateAccountName);
  // 将 formData 返回给 el-upload 使用
  return formData;
};

const fileList = ref([]);
const handleUploadSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  console.log("通过excel上传歌曲---成功后--请求列表");
  console.log(response);
  ElNotification({
    title: "新消息",
    message: "EXCEL文件正在处理中...",
    type: "primary",
    position: "bottom-right",
    onClick: () => {
      // 点击通知的处理逻辑
      // console.log('通知被点击', message);
    },
  });
  fileList.value = [];
  loading.close();
  getData();
};

let loading2 = null;
const beforeUpload2 = (file) => {
  loading2 = ElLoading.service({
    lock: true,
    text: "上传中",
    background: "rgba(0, 0, 0, 0.7)",
  });
  const formData = new FormData();
  formData.append("file", file);
  // 可以添加其他字段
  formData.append("operateAccountId", "admin");
  formData.append("operateAccountName", "系统管理员");
  // 将 formData 返回给 el-upload 使用
  return formData;
};

const handleUploadSuccess2: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  console.log("通过excel上传歌曲---成功后--请求列表");
  console.log(response);
  loading2.close();
  getData();
};

// 设为上新推荐
const handleSetRecommended = async (row) => {
  console.log("歌曲-设为上新推荐");
  let params = {
    songId: row.songId,
  };
  const res = await fetchSetRecommended(params);
  if (res.data.code === 0) {
    ElMessage.success("设置成功");
    getData();
  } else {
    ElMessage.error(res.data.msg);
  }
};
// 移除上新推荐
const handleYichRecommended = async (row) => {
  console.log("歌曲-移除上新推荐");
  let params = {
    songId: row.songId,
  };
  const res = await fetchDeleteRecommended(params);
  if (res.data.code === 0) {
    ElMessage.success("移除成功");
    getData();
  } else {
    ElMessage.error(res.data.msg);
  }
};

const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: any;
  rowIndex: number;
}) => {
  if (row.haveSongFile === 0) {
    return "success-row";
  }
  return "";
};

// WebSocket相关--------
// const { isConnected, realTimeData, initWebSocket, sendMessage } =
//   useWebSocketRealTime();

onMounted(() => {
  //   console.log("链接websocket中...");
  //   console.log(JSON.parse(localStorage.getItem("userInfo")).userId);
});
let connectUrl = `ws://129.204.225.193:8892/chat/${
  JSON.parse(localStorage.getItem("userInfo")).userId
}`;
const { messages, isConnected, sendMessage } = useWebSocket(connectUrl);
// console.log("接受到的websocket消息");
// console.log(messages);
watch(
  messages,
  (newVal, oldVal) => {
    console.log("接受到的websocket消息变化");
    console.log(newVal);
    console.log(oldVal);
    getData();
  },
  { deep: true }
);

// ElNotification.error({
//   title: "连接失败",
//   message: "WebSocket连接建立失败，请检查网络或服务器状态",
//   duration: 3000,
// });
// ElNotification({
//   title: "新消息",
//   message: "kkk",
//   type: "primary",
//   position: "bottom-right",
//   onClick: () => {
//     // 点击通知的处理逻辑
//     // console.log('通知被点击', message);
//   },
// });

// 在这里你可以监听消息，或者发送消息
</script>

<style scoped>
.zhuanj {
  width: 100px;
  height: 100px;
  margin: 10px auto;
  position: relative;
  /* cursor: pointer; */
}
.avatar {
  width: 100px;
  height: 100px;
  margin: 0 auto;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center center;
  /* cursor: pointer; */
}
.zhuanj_bg {
  width: 100px;
  height: 100px;
  margin: 0 auto;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 9;
}
.zhuanj_img1 {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 9;
  width: 70px;
  height: auto;
  margin-left: 15px;
  margin-top: 15px;
}
.zhuanj_img2 {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 9;
  width: 70px;
  height: auto;
  margin-left: 15px;
  margin-top: 15px;
}
::v-deep .el-form-item__label {
  line-height: normal;
  align-items: center;
}
.el-form-item__label {
  line-height: normal !important;
  align-items: center !important;
}
.daoru {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.daoru2 {
  display: flex;
  justify-content: space-between;
}
::v-deep .table-toolbar-left {
  width: 100% !important;
  margin-bottom: 10px;
}
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>
